package com.mall.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mall.utils.StringUtils;
import com.mall.vo.ResultVO;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class CheckTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if ("OPTIONS".equals(method)){
            return true;
        }
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)){
            doResponse(response,ResultVO.fail(203,"token不能为空！"));
            return false;
        }else {
            try{
                JwtParser parser = Jwts.parser();
                parser.setSigningKey("mall666");
                Jws<Claims> claimsJws = parser.parseClaimsJws(token);
                return true;

            }catch(ExpiredJwtException e){
                doResponse(response,ResultVO.fail(202,"登录已过期，请重新登录！"));
                return false;
            }catch(Exception e){
                doResponse(response,ResultVO.fail("token不合法，请重新登录！"));
                return false;
            }

        }

    }
    private void doResponse(HttpServletResponse response,ResultVO resultVO) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String s = new ObjectMapper().writeValueAsString(resultVO);
        out.println(s);
        out.flush();
        out.close();
    }
}
















